package com.biubiux2.security;

import com.biubiux2.message.MessageType;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author noexcs
 * @since 8/9/2022 10:54 PM
 */
public class KeyNegotiationContext {

    public static final AttributeKey<KeyNegotiationContext> KEY_NEGOTIATION_CONTEXT_ATTRIBUTE_KEY = AttributeKey.valueOf("KEY_NEGOTIATION_CONTEXT_ATTRIBUTE_KEY");

    public PrivateKey privateKey;

    public PublicKey publicKey;

    public void negotiate(ChannelHandlerContext ctx){
        // 生成公私钥
        KeyPair keyPair = RSAUtil.getKeyPair();
        privateKey = keyPair.getPrivate();
        publicKey = keyPair.getPublic();
        String publicKeyStr = RSAUtil.ConvertKeyToString(publicKey);

        // 发送公钥
        byte[] outBytes = publicKeyStr.getBytes(StandardCharsets.UTF_8);
        ByteBuf buffer = PooledByteBufAllocator.DEFAULT.buffer(4 + outBytes.length);
        buffer.writeInt(MessageType.CLIENT_PUBLIC_KEY);
        buffer.writeBytes(outBytes);
        ctx.writeAndFlush(buffer);
    }
}
